#include<unistd.h>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>

int main(){
    int pfd[2];
    int pid1, pid2;
    char buf[1024];
    int res = pipe(pfd);
    if(res == EOF){
        perror("pipe");
        return 1;
    }

    pid1 = fork();
    if(pid1 == EOF){
        perror("fork");
        return 1;
    }

    if(pid1 == 0){
        char* msg = "hello, I am child1 process!";
        strncpy(buf, msg,strlen(msg));
        buf[strlen(msg)] = '\0';
        write(pfd[1],buf, strlen(msg)+1);
        close(pfd[1]);
        exit(0);
    }else if(pid1 > 0){
        pid2 = fork();
        if(pid2 == EOF){
            perror("fork");
            return 1;
        }

        if(pid2 == 0){
            sleep(2);
            char* msg = "hello, I am child2 process!";
            strncpy(buf, msg,strlen(msg));
            buf[strlen(msg)] = '\0';
            write(pfd[1],buf, strlen(msg)+1);
            //管道不用之后关闭使用的一端
            close(pfd[1]);
            exit(0);
        }

        if(pid2 > 0){
            wait(NULL);
            char read_buf[1024];
            read(pfd[0], read_buf, sizeof(read_buf));
            printf("read from pipe: %s\n", read_buf);
            wait(NULL);
            read(pfd[0], read_buf, sizeof(read_buf));
            printf("read from pipe: %s\n", read_buf);
            printf("parent process exit");
            close(pfd[0]);
            exit(0);
        }
    }

    return 0;
}